const path = require('path'); // ✅ 新增
const fs = require('fs');
const yaml = require('js-yaml');
const MySQLDatabase = require("../utils/dbconfig");
const { formatTimeToChinaTime } = require("../utils/tools");
const { sendPrivateMessageToUser } = require("../telegramAuth");

let mysqlConfig = {};

try {
    const fileContents = fs.readFileSync(path.resolve(__dirname, '../config.yml'), 'utf8');
    const config = yaml.load(fileContents);
    mysqlConfig = config.mysql;
    // console.log('✅ 配置加载成功:', mysqlConfig);
} catch (e) {
    console.error('❌ 读取配置失败:', e);
}

const db = new MySQLDatabase({
    host: mysqlConfig.host,
    user: mysqlConfig.username,
    password: mysqlConfig.pwd, // ✅ 修复此处
    database: mysqlConfig.database
});


async function queryAllMes() {
    let sql = "SELECT * FROM message_sending_record"
    try {
        const result = await db.query(sql)
        // 格式化 creation_time
        const formattedResult = result.map(item => ({
            ...item,
            creation_time: formatTimeToChinaTime(item.creation_time)
        }));
        return formattedResult
    } catch (err) {
        return "查询失败"
    }
}

/**
 * 
 * @param {*} group_id  群组ID
 * @param {*} group_name 群组名称
 * @param {*} state 发送状态 
 * @param {*} key_wrod 触发关键字
 * @param {*} msg 发送私聊消息
 * @param {*} user_id 用户ID
 * @param {*} access_hash 用户哈希ID
 * @returns 
 */
async function insertMsgRecord(group_id, group_name, state, key_wrod, msg, user_id, access_hash) {
    const keys = {
        state: state,
        group_id: group_id,
        group_name: group_name,
        key_wrod: key_wrod,
        msg: msg,
        user_id: user_id,
        access_hash: access_hash,
    };
    try {
        const result = await db.insert('message_sending_record', keys);
        return "新增成功";
    } catch (err) {
        return err.sqlMessage;
    }
}

async function queryMsgById(id) {
    const sql = "SELECT * FROM message_sending_record WHERE id = ?";
    try {
        const result = await db.query(sql, [id]);

        if (result.length === 0) {
            return null; // 或返回 "未找到对应记录"
        }

        // 格式化时间字段
        result[0].creation_time = formatTimeToChinaTime(result[0].creation_time);
        return result[0];
    } catch (err) {
        return `查询失败: ${err.message}`;
    }
}

/**
 * 重新发送消息
 * @param {*} id 记录ID
 * @param {*} client 客户端
 */
async function resetSendMsg(id, client) {
    let result = await queryMsgById(id)
    // console.log(result.access_hash)
    // console.log(result.user_id)
    let success = await sendPrivateMessageToUser(client, result.user_id, result.access_hash, result.msg)
    if (success) {
        // console.log("群聊名称：", title)
        // console.log(`✅ 私聊发送成功 - 群: ${title} 用户: ${userId}`);
        // await insertMsgRecord(groupId, title, "成功", olmsg, msg, userId, accessHash)
        return true
    } else {
        // console.error(`❌ 私聊发送失败 - 群: ${title} 用户: ${userId}`);
        // await insertMsgRecord(groupId, title, "失败", olmsg, msg, userId, accessHash)
        return false
    }
}

// (async () => {
//     await queryAllMes().then((res)=>{
//         console.log(res)
//     })

//     // let result = insertMsgRecord("11","测试","cs","萨达","123123","asdasd").then(()=>{
//     //     console.log("添加成功")
//     // })
//     // console.log(result)



// })();

module.exports = {
    queryAllMes,
    insertMsgRecord,
    resetSendMsg
}